<template>
  <div class="note-sidebar">
    <span class="button add-note" @click="onAddNote">添加笔记</span>
    <el-dropdown class="notebook-title" @command="handleCommand" placement="bottom">
      <span class="el-dropdown-link">
        {{ curBook.title }}
         <svg class="icon">
          <use xlink:href="#icon-arrow"></use>
        </svg>
      </span>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item v-for="notebook in notebooks" :key="notebook.id" :command="notebook.id">
            {{ notebook.title }}
          </el-dropdown-item>
          <el-dropdown-item command="trash">回收站</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
    <div class="menu">
      <div>更新时间</div>
      <div>标题</div>
    </div>
    <ul class="notes">
      <li v-for="note in notes" :key="note">
        <router-link :to="`/note?noteId=${note.id}&notebookId=${curBook.id}`">
          <span class="date">{{ note.updatedAtFriendly }}</span>
          <span class="title">{{ note.title }}</span>
        </router-link>
      </li>
    </ul>
  </div>
</template>

<script>

import {mapGetters, mapActions, mapMutations} from 'vuex'


export default {
  created() {
    this.getNotebooks().then(() => {
      this.setCurBook({curBookId: this.$route.query.notebookId})
      return this.getNotes({notebookId: this.curBook.id})
    }).then(() => {
      this.setCurNote({curNoteId: this.$route.query.noteId})
      this.$router.replace({
        path: '/note',
        query: {
          noteId: this.curNote.id,
          notebookId: this.curBook.id
        }
      })
    })
  },
  data() {
    return {}
  },
  computed: {
    ...mapGetters([
      'notebooks',
      'notes',
      'curBook',
      'curNote'
    ])
  },
  methods: {
    ...mapMutations([
      'setCurBook',
      'setCurNote'
    ]),
    ...mapActions([
      'getNotebooks',
      'getNotes',
      'addNote'
    ]),
    handleCommand(notebookId) {
      if (notebookId == 'trash') {
        return this.$router.push({path: '/trash'})
      }
      this.$store.commit('setCurBook', {curBookId: notebookId})
      this.getNotes({notebookId}).then(() => {
        this.setCurNote({})
        this.$router.replace({
          path: '/note',
          query: {
            noteId: this.curNote.id,
            notebookId: this.curBook.id
          }
        })
      })
    },
    onAddNote() {
      this.addNote({notebookId: this.curBook.id})
    }
  }
}

</script>

<style lang="less">
@import url(../assets/css/note-sidebar);

#note {
  display: flex;
  align-items: stretch;
  background-color: #fff;
  flex: 1;
}

.icon {
  width: 10px;
  height: 10px;
}
</style>
